package dpss.frontend;

import java.net.DatagramSocket;
import java.util.ArrayList;
import java.util.List;

import dpss.commons.CustomLogger;
import dpss.commons.UDPMessage;

/**
 * THE UDP PORT LISTENER FOR FRONT END
 * 
 * Listens to the incoming UDP requests and acts accordingly
 * @author musab.mirza
 *
 */
public class UDPListener extends Thread{
	
	private static CustomLogger logger = CustomLogger.getInstance();
	
	
	private DatagramSocket socket;
	private List<UDPMessage> dpssResponseCache;

	
	public UDPListener(DatagramSocket socket, List<UDPMessage> dpssResponseCache2){
		this.socket = socket;
		this.dpssResponseCache = dpssResponseCache2;
	}
	
	/**
	 * Runner
	 */
	public void run(){
		
		logger.log("Started the UDP listener to listen for DPSS responses");
		
		for(;;){
			UDPMessage dpssResponse = UDPMessage.receiveUDPMessage(socket);
			logger.log("Received DPSS response from " + dpssResponse.getSenderSocketAddress().toString() + " titled: " + dpssResponse.getMessage() + ". Reponse added to Response cache.");
			synchronized(dpssResponseCache){
				dpssResponseCache.add(dpssResponse);
				printDpssResponseCache();
			}
		}
	}

	/**
	 * Prints the current DPSS cache to console
	 */
	private synchronized void printDpssResponseCache() {
		String cachePrint = "\n\n---- DPSS RESPONSE CACHE ("+dpssResponseCache.size()+") -----";
		for(UDPMessage m : dpssResponseCache){
			cachePrint = cachePrint + "\n" + m.toString();
		}
		cachePrint = cachePrint + "\n----------------------------------\n";
		logger.log(cachePrint);
	}

}
